//
//  PublishVC.swift
//  WBSwift
//
//  Created by maker on 2016/11/18.
//  Copyright © 2016年 maker. All rights reserved.
//

import UIKit
import SVProgressHUD

class PublishVC: UIViewController {
    
    var titleView : PublishTitleView?                   // 标题
    fileprivate lazy var images : [UIImage] = [UIImage]()   //图片的数据源
    fileprivate lazy var emotionBoard : EmotionVC = EmotionVC {[weak self] (emotion) in
        self?.textView.insertEmotion(emotion)
        //textView 插入表情的时候并没有触发系统的 textChange 方法,手动调用一下
        self?.textViewDidChange((self?.textView)!)
    }
    @IBOutlet weak var textView: PublishTextView!       //输入框
    @IBOutlet weak var picCollectionView: PicPickerCollection!
    
    
    @IBOutlet weak var toolBarBot: NSLayoutConstraint!
    @IBOutlet weak var collectH: NSLayoutConstraint!

    //MARK:==========声明周期==========
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavgationBar()
        regsiterNotification()

    }
    override func viewDidAppear(_ animated: Bool) {
        textView.becomeFirstResponder()
    }
    deinit {
        NotificationCenter().removeObserver(self)
    }
}

//MARK:==========设置 UI ==========
extension PublishVC{
    
    //1.设置导航条
    func setNavgationBar() {
        //1.设置左右按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .done, target: self, action: #selector(PublishVC.rightClick))
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(PublishVC.leftClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        //2.标题
        titleView = PublishTitleView(frame: CGRect(x: 0, y: 0, width: screenWidth - 200, height: 44))
        navigationItem.titleView = titleView
    }
    
    //2.注册通知
    func regsiterNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(PublishVC.keyboardWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(PublishVC.openAblum), name: NSNotification.Name(rawValue: AddPhotoNotice), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(PublishVC.removePhoto(_:)), name: NSNotification.Name(rawValue: RemovePhotoNotice), object: nil)
    }
}

//MARK:==========事件监听==========
extension PublishVC{
    
    @objc fileprivate  func rightClick() {
        //1.键盘关闭卡顿先关闭键盘
        textView.resignFirstResponder()
        
        //2.定义一个结果闭包
        let callBack : (_ isSuccess:Bool) -> () = { isSuccess in
            
            if isSuccess
            {
                SVProgressHUD.showSuccess(withStatus: "发送微博成功")
                self.dismiss(animated: true, completion: nil)
            }else
            {
                SVProgressHUD.showError(withStatus: "发送微博失败")
            }
        }
        
        //3.判断是否有图片发送网络请求
        if let firstImage = images.first {
            
            NetWorkTool.shareInstance.sendImageStaus(textView.getEmotionStr(), image: firstImage, isSucess: callBack)
            
        }else
        {
            NetWorkTool.shareInstance.sendStatus(textView.getEmotionStr(), isSucess: callBack)
        }
        
    }
    @objc fileprivate  func leftClick() {
        dismiss(animated: true, completion: nil)
    }
    
    //键盘监听
    func keyboardWillChangeFrame(_ notification : Notification) {

        guard let userDict = notification.userInfo else {
            return
        }
        let duration : TimeInterval = userDict["UIKeyboardAnimationDurationUserInfoKey"] as! TimeInterval
        let endRect : CGRect = (userDict["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        
        //创建动画
        self.toolBarBot.constant = screenHeight - endRect.origin.y
         UIView.animate(withDuration: duration, animations: { 
            self.view.layoutIfNeeded() //先改变数值之后,在动画内重新布局页面
        }) 
        
    }
    
    //相册点击
    @IBAction func picPickerClick(_ sender: UIButton) {
        textView.resignFirstResponder()
        //弹出集合视图
        collectH.constant = screenHeight * 0.65
        UIView.animate(withDuration: 0.5, animations: {
            self.view.layoutIfNeeded()
        }) 
    }
    
    //通知控制器打开相册
    func openAblum()  {
        //1.判断相册资源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        
        //2.创建相册控制器
        let picVC = UIImagePickerController.init()
        
        //3.设置相册控制器的资源类型
        picVC.sourceType = .photoLibrary
        
        //4.设置代理
        picVC.delegate = self
        
        //5.显示图片控制器
        present(picVC, animated: true, completion: nil)
        
    }
    
    //通知移除图片
    func removePhoto(_ notification : Notification) {
        guard let objects = notification.object else {
            return
        }
        let removeImage = objects as! UIImage
        
        guard let index = images.index(of: removeImage) else {
            return
        }
        images.remove(at: index)
        picCollectionView.images = images
    }
    
    //监听表情点击
    @IBAction func emojiClick(_ sender: UIButton) {
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emotionBoard.view : nil
        textView.becomeFirstResponder()
    }
}

//MARK:==========textView的代理==========
extension PublishVC : UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeHolderLbl.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.textView.resignFirstResponder()
    }
}

//MARK:========== 相册代理 ==========
extension PublishVC : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        images.append(image)
        picCollectionView.images = images
        picker.dismiss(animated: true, completion: nil)
    }
    
}





